<template>
  <div class="log-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h3>操作日志</h3>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-form :model="searchForm" inline>
            <el-form-item label="操作人">
              <el-input
                  v-model="searchForm.operatorName"
                  placeholder="请输入操作人姓名"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="操作类型">
              <el-select
                  v-model="searchForm.operationType"
                  placeholder="请选择操作类型"
                  clearable
                  style="width: 120px"
              >
                <el-option
                    v-for="(text, value) in OPERATION_TYPE_TEXT"
                    :key="text"
                    :label="text"
                    :value="text"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="操作描述">
              <el-input
                  v-model="searchForm.operation"
                  placeholder="请输入操作描述"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="时间范围">
              <el-date-picker
                  v-model="searchForm.dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 350px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button
              type="danger"
              :disabled="selectedLogs.length === 0"
              @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selectedLogs.length }})
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ pagination.total }}</div>
            <div class="stat-label">总日志数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ todayLogCount }}</div>
            <div class="stat-label">今日日志</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ operationTypeCount }}</div>
            <div class="stat-label">操作类型数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ selectedLogs.length }}</div>
            <div class="stat-label">已选择</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 日志表格 -->
    <div class="table-section">
      <el-table
          ref="tableRef"
          v-loading="loading"
          :data="logList"
          @selection-change="handleSelectionChange"
          stripe
          border
          style="width: 100%"
          empty-text="暂无日志数据"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="operation" label="操作描述" min-width="100" show-overflow-tooltip />
        <el-table-column prop="operationType" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="OPERATION_TYPE_TAG_TYPE[row.operationType]">
              {{ OPERATION_TYPE_TEXT[row.operationType] || row.operationType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operatorName" label="操作人" width="100" />
        <el-table-column prop="operatorIp" label="操作IP" width="140" />
        <el-table-column prop="params" label="参数" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.params" class="params-text">{{ row.params }}</span>
            <span v-else class="no-params">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="操作时间" width="180" sortable />
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete } from '@element-plus/icons-vue'
import { logApi } from '../api/log'
import {
  OPERATION_TYPE_TEXT,
  OPERATION_TYPE_TAG_TYPE,
  OPERATION_TYPE
} from '../utils/constants'

export default defineComponent({
  name: 'LogList',
  components: {
    Search,
    Refresh,
    Delete
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const logList = ref([])
    const selectedLogs = ref([])
    const tableRef = ref()

    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    const searchForm = reactive({
      operatorName: '',
      operationType: '',
      operation: '',
      dateRange: null
    })

    // 计算属性
    const todayLogCount = computed(() => {
      const today = new Date().toDateString()
      return logList.value.filter(log => {
        const logDate = new Date(log.createdAt).toDateString()
        return logDate === today
      }).length
    })

    const operationTypeCount = computed(() => {
      const types = new Set(logList.value.map(log => log.operationType))
      return types.size
    })

    // 获取日志列表
    const getLogList = async () => {
      try {
        loading.value = true
        const params = {
          page: pagination.current,
          size: pagination.size,
          ...searchForm
        }

        // 处理时间范围
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          params.startTime = searchForm.dateRange[0]
          params.endTime = searchForm.dateRange[1]
          delete params.dateRange
        }

        const response = await logApi.getLogList(params)
        logList.value = response.records || response.list || []
        pagination.total = response.total || 0

      } catch (error) {
        console.error('获取日志列表失败:', error)
        ElMessage.error('获取日志列表失败')
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      getLogList()
    }

    // 重置搜索
    const handleReset = () => {
      Object.assign(searchForm, {
        operatorName: '',
        operationType: '',
        operation: '',
        dateRange: null
      })
      pagination.current = 1
      getLogList()
    }

    // 删除日志
    const handleDelete = async (row) => {
      try {
        await logApi.deleteLog(row.id)
        ElMessage.success('删除成功')
        getLogList()

      } catch (error) {
        console.error('删除日志失败:', error)
        ElMessage.error('删除日志失败')
      }
    }

    // 批量删除
    const handleBatchDelete = async () => {
      if (selectedLogs.value.length === 0) {
        ElMessage.warning('请选择要删除的日志')
        return
      }

      try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedLogs.value.length} 条日志吗？此操作不可恢复！`,
            '批量删除确认',
            {
              confirmButtonText: '确定删除',
              cancelButtonText: '取消',
              type: 'warning',
              dangerouslyUseHTMLString: true
            }
        )

        const ids = selectedLogs.value.map(log => log.id)
        await logApi.batchDeleteLogs(ids)
        ElMessage.success(`成功删除 ${selectedLogs.value.length} 条日志`)
        getLogList()

      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    }

    // 表格选择变化
    const handleSelectionChange = (selection) => {
      selectedLogs.value = selection
    }

    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
      getLogList()
    }

    // 当前页变化
    const handleCurrentChange = (current) => {
      pagination.current = current
      getLogList()
    }

    // 组件挂载时获取数据
    onMounted(() => {
      getLogList()
    })

    return {
      loading,
      logList,
      selectedLogs,
      tableRef,
      pagination,
      searchForm,
      todayLogCount,
      operationTypeCount,
      OPERATION_TYPE_TEXT,
      OPERATION_TYPE_TAG_TYPE,
      OPERATION_TYPE,
      getLogList,
      handleSearch,
      handleReset,
      handleDelete,
      handleBatchDelete,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange
    }
  }
})
</script>

<style scoped>
.log-list-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-header h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.text-right {
  text-align: right;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 20px;
}

.params-text {
  color: #606266;
  font-size: 12px;
}

.no-params {
  color: #c0c4cc;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-section .el-col {
    margin-bottom: 10px;
  }

  .text-right {
    text-align: left;
  }

  .el-table {
    font-size: 12px;
  }

  .stats-section .el-col {
    margin-bottom: 10px;
  }
}
</style>
